package com.longkier.gx_library_springboot.Controller;

import com.longkier.gx_library_springboot.Service.BooksBorrowService;
import com.longkier.gx_library_springboot.entity.BooksBorrow;
import com.longkier.gx_library_springboot.exception.CustomException;
import com.longkier.gx_library_springboot.utils.RequestUtils;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@RestController
@RequiredArgsConstructor
@RequestMapping("/borrow")
@CrossOrigin(origins = "http://localhost:5173", allowCredentials = "true")
public class BooksBorrowController {
    private static final Logger logger = LoggerFactory.getLogger(BooksBorrowController.class);
    private final BooksBorrowService booksBorrowService;

    /**
     * 借阅图书
     *
     * @param booksBorrow 图书借阅信息
     * @return 借阅结果
     */
    @PostMapping("/lend")
    public Map<String, Object> borrowBook(@RequestBody BooksBorrow booksBorrow) {
        try {
            booksBorrowService.borrowBook(booksBorrow);
            return RequestUtils.buildResponse("借阅成功", 200);
        } catch (Exception e) {
            logger.error("内部错误: {}", e.getMessage(), e);
            throw new CustomException(500, "借阅图书时发生异常");
        }
    }

    /**
     * 根据借阅ID归还图书
     *
     * @param borrowId 借阅ID
     * @return 归还结果
     */
    @PutMapping("/return/{borrowId}")
    public Map<String, Object> returnBook(@PathVariable Long borrowId) {
        try {
            boolean success = booksBorrowService.returnBook(borrowId);
            if (success) {
                return RequestUtils.buildResponse("归还成功", 200);
            } else {
                return RequestUtils.buildResponse("借阅记录不存在",404);
            }
        } catch (Exception e) {
            throw new CustomException(500, "归还图书时发生异常");
        }
    }

    /**
     * 根据借阅ID续借图书
     *
     * @param borrowId 借阅ID
     * @return 续借结果
     */
    @PutMapping("/renew/{borrowId}")
    public Map<String, Object> renewBook(@PathVariable Long borrowId) {
        try {
            boolean success = booksBorrowService.renewBook(borrowId);
            if (success) {
                return RequestUtils.buildResponse("续借成功", 200);
            } else {
                return RequestUtils.buildResponse("借阅记录不存在或已归还、已逾期", 404);
            }
        } catch (Exception e) {
            logger.error("内部错误: {}", e.getMessage(), e);
            throw new CustomException(500, "续借图书时发生异常");
        }
    }

    /**
     * 处理逾期借阅记录
     *
     * @param borrowId 借阅ID
     * @param violationNote 违规记录
     * @return 处理结果
     */
    @PutMapping("/overdue/{borrowId}")
    public Map<String, Object> handleOverdue(@PathVariable Long borrowId, @RequestParam String violationNote) {
        try {
            boolean success = booksBorrowService.handleOverdue(borrowId, violationNote);
            if (success) {
                return RequestUtils.buildResponse("逾期处理成功", 200);
            } else {
                return RequestUtils.buildResponse("借阅记录不存在或未逾期", 404);
            }
        } catch (Exception e) {
            logger.error("内部错误: {}", e.getMessage(), e);
            throw new CustomException(500, "处理逾期借阅记录时发生异常");
        }
    }



    /**
     * 查询所有借阅记录
     *
     * @param request 请求体，包含分页信息
     * @return 借阅记录列表
     */
    @PostMapping("/all")
    public Map<String, Object> getAllBorrowedBooks(@RequestBody Map<String, Object> request) {
        int page = (int) request.getOrDefault("page", 0);
        int size = (int) request.getOrDefault("size", 10);
        try {
            return RequestUtils.buildResponse(booksBorrowService.getAllBorrowedBooks(page, size), 200);
        } catch (Exception e) {
            logger.error("内部错误: {}", e.getMessage(), e);
            throw new CustomException(500, "查询借阅记录时发生异常");
        }
    }

    /**
     * 根据借阅卡号查询借阅信息
     *
     * @param cardNumber 借阅卡号
     * @return 借阅信息
     */
    @GetMapping("/{cardNumber}")
    public Map<String, Object> getBorrowInfo(@PathVariable String cardNumber) {
        try {
            List<BooksBorrow> booksBorrow = booksBorrowService.getBorrowInfo(cardNumber);
            if (booksBorrow != null) {
                return RequestUtils.buildResponse(booksBorrow, 200);
            } else {
                return RequestUtils.buildResponse( "借阅记录不存在",404);
            }
        } catch (Exception e) {
            logger.error("内部错误: {}", e.getMessage(), e);
            throw new CustomException(500, "查询借阅记录时发生异常");
        }
    }
}
